package iNotes;

import iNotes.assist.DataPool;
import iNotes.assist.Utils;
import org.apache.commons.lang3.RandomStringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;

@WebServlet(name = "SignIn", value = "/SignIn")
public class SignIn extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        return;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userName = request.getParameter("uname");
        String password = request.getParameter("pwd");
        HttpSession session = request.getSession();

        Connection connection = null;
        CallableStatement callableStatement = null;
        Integer id = null;
        try {
            connection = DataPool.ds.getConnection();
            callableStatement = connection.prepareCall("{call checkSignin(?,?,?)}");
            callableStatement.setString(1,userName);
            callableStatement.setString(2,password);
            callableStatement.registerOutParameter(3, Types.INTEGER);
            callableStatement.execute();
            id = callableStatement.getInt(3);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            Utils.close(connection,null,callableStatement);
        }
        if (id != 0) {
            session.setAttribute("signIn", "true");
            session.setAttribute("uname", userName);
            session.setAttribute("uid", id);
            session.setAttribute("_token", RandomStringUtils.randomAlphanumeric(16));
            response.sendRedirect("notes.jsp");
        } else {
            session.setAttribute("signIn", "false");
            response.sendRedirect("index.jsp");
        }
    }
}
